/*
* created by Administrator on 2018/11/30
* 好的代码像粥一样,是得用时间和精力熬的。
*/
const models = require('../database/model');
const querystring = require('querystring');
const Mock = require('mockjs');
const request = require('request'); // 发送http请求
const Router = require('koa-router');  // 路由中间件
const router = new Router();
router.get('/validCodeMsg', async (ctx, next) => {
    let {phoneNumber} = ctx.request.query;
    if(phoneNumber && /^1[35789]\d{9}$/.test(phoneNumber)){
        function random() {
            return parseInt(Math.random() * 1000000) + '';
        }
        let code = random();
        ctx.session.user = {
            tel: phoneNumber,
            code: code
        };
        var querydata = querystring.stringify({
            mobile: phoneNumber,
            tpl_id: 117376,
            tpl_value: '#code#='+code,
            key: '098612e22e290c18262c3a8b48d7edb5'
        });
        let url = `http://v.juhe.cn/sms/send?${querydata}`;
        let ajax = async (url) => {
            return new Promise((resolve, reject)=>{
                request(url, (error, res, body) => {
                    let code = JSON.parse(body);
                    if(code.error_code === 0) {
                        resolve(code);
                    }else {
                        reject(code);
                    }
                })
            })
        };
        await ajax(url).then(()=>{
            ctx.body = {
                code: 1,
                msg: `验证码发送成功!`
            }
        }).catch(() => {
            ctx.body = {
                code: -1,
                msg: `验证码发送失败!`
            }
        })
    }
    await next();
});
router.get('/valid', async (ctx, next) => {
    let {code} = ctx.request.query;
    console.log(ctx.session.user);
    if(ctx.session.user){
        if(ctx.session.user.code === code){
            ctx.body = {
                code: 1,
                msg: '注册成功，写入数据库'
            }
        }else{
            ctx.body = {
                code: -1,
                msg: '验证码错误'
            }
        }
    }else{
        ctx.body = {
            code: -1,
            msg: '请现输入手机号'
        }
    }
    await next();
});
router.get('/login', async (ctx, next) => {
    let {username, password} = ctx.request.query;
    if(username === 'a' && password === '123') {
        ctx.session.user = {username, password};
        ctx.body = {
            code: 1,
            msg: '登录成功!'
        }
    }else{
        ctx.body = {
            code: -1,
            msg: '用户名或密码错误'
        }
    }
    await next();
});
router.get('/test', async (ctx, next) => {
    if(ctx.session.user){
        ctx.body = {
            code: 1,
            msg: '我认识你'
        }
    }else{
        ctx.body = {
            code: -1,
            msg: '请登录'
        }
    }
    await next();
});
router.get('/unlogin', async (ctx, next) => {
   if(ctx.session.user) {
       ctx.session.user = null;
       ctx.body = {
           code: 1,
           msg: '退出登录成功!'
       }
   } else {
       ctx.body = {
           code: -1,
           msg: '你是不是憨'
       }
   }
   await next();
});
// router.get('/reg', async (ctx, next) => {
//     let {username, password, phoneNumber} = ctx.request.query;
//     if (username && password && phoneNumber){
//       await models.User.create({username, password, phoneNumber})
//             .then(data => {
//                 ctx.body = {
//                     code: 1,
//                     msg: '注册成功！',
//                     data
//                 }
//             })
//             .catch(error => {
//                 ctx.body = {
//                     code: -1,
//                     msg: '注册失败！',
//                     error
//                 }
//             })
//     }else {
//         ctx.body = {
//             code: -1,
//             msg: '数据不合格'
//         }
//     }
//     await next();
// } );
router.get('/repeat', async (ctx, next) => {
    Mock.mock({
        "data|10000":[{
            username:'@cname',
            gender: '@boolean',
            age: '@integer(14,50)',
            phoneNumber: /^1[35798]\d{9}$/,
            city: '@city',
            password: /^[A-Z]\w{9,15}$/
        }]
    }).data.forEach(async (v) => {
        await models.User.create(v)
            .then( data => {
                console.log(data);
            } )
            .catch( err => {
                console.log(err)
            })
    })
});

router.get('/search', async (ctx, next) => {
    let {searchText} = ctx.request.query;
    searchText !== '' && await models.User.find({
        $or: [
            {username: new RegExp(searchText)},
            {phoneNumber: new RegExp(searchText)},
            {city: new RegExp(searchText)},
        ]
    }).limit(100)
        .then(function (data) {
            console.log(data);
            ctx.body = {
                code: 1,
                msg: '搜索成功',
                data
            }
        })
        .catch(function (error) {
            console.log(error);
            ctx.body = {
                code: -1,
                msg: '搜索失败',
                error
            }
        });
    await next()
});
module.exports = app => app.use(router.routes());
